import {
  IMAGE_HOST_TEST,
  IMAGE_HOST_PROD
} from '../constants'
import { message } from 'antd'
import _ from 'lodash'

export const noop = function noop() {}

export function createReducer(initialparams, reducerMap) {
  return (params = initialparams, action) => {
    const reducer = reducerMap[action.type]

    return reducer ? reducer(params, action.payload ? action.payload : {}, action.params) : params
  }
}

export function clone (Obj){
  let buf
  if(Obj!=null && (!!Obj.asImmutable || Obj._isValid != undefined)){
    //Immutable
    return Obj
  }
  if (Obj instanceof Array) {
    buf = []  // 创建一个空的数组
    let i = Obj.length
    while (i--) {
      buf[i] = clone(Obj[i])
    }
    return buf
  } else if (Obj instanceof Object){
    buf = {}  // 创建一个空对象
    for (let k in Obj) {  // 为这个对象添加新的属性
      buf[k] = clone(Obj[k])
    }
    return buf
  }else{
    return Obj
  }
}

/**
 * fixNumber(date)
 *
 * desc：
 * 修复时间字符串，判断时间长度是否满足要求，不满足则根据长度差距在其末尾不足 '0'
 *
 * 参数：
 * `date` 时间 String
 *
 * 默认 `dataLength` = 13
 */
const fixNumber = function(date) {
  const dateLength = 13
  const len = date.length

  let diffLen = dateLength - len
  let diff = ''

  while (diffLen) {
    diff += '0'
    diffLen--
  }

  return date + diff
}

/**
 * dateFormat(data, format)
 *
 * desc：
 * 时间格式化，默认为 `yyyy-MM-dd` 类型
 *
 * 懵逼了，需要啃下 `es6` 语法。。。
 *
 * */
export function dateFormat(date, format) {
  let _format = format || 'yyyy-MM-dd'

  const d = date
  const o = {
    'M+': d.getMonth() + 1, // month
    'd+': d.getDate(), // day
    'h+': d.getHours(), // hour
    'm+': d.getMinutes(), // minute
    's+': d.getSeconds(), // second
    'q+': Math.floor((d.getMonth() + 3) / 3), // quarter
    'S': d.getMilliseconds() // millisecond
  }

  /**
     * `repeat` 方法返回一个新字符串，表示将原字符串重复 `n` 次。
     *
     * `RegExp` 是javascript中的一个内置对象。为正则表达式。
     * `RegExp.$1` 是 `RegExp` 的一个属性,指的是与正则表达式匹配的第一个 子匹配(以括号为标志)字符串
     * 以此类推，RegExp.$2，RegExp.$3，..RegExp.$99总共可以有99个匹配
     *
     * 例子：
     * var r= /^(\d{4})-(\d{1,2})-(\d{1,2})$/; //正则表达式 匹配出生日期(简单匹配)
     * r.exec('1985-10-15');
     * s1=RegExp.$1;
     * s2=RegExp.$2;
     * s3=RegExp.$3;
     * alert(s1+" "+s2+" "+s3)//结果为1985 10 15
     *
     * `test()` 方法用于检测一个字符串是否匹配某个模式.
     * 语法：RegExpObject.test(string)
     *
     */

  /**
     * 使用正则匹配年份：
     *
     * 1、 /(y+)/.test(_format)
     * - 检测： `_format` 中最少有一个 `y` // 正则： `+` 表示最少要有一个； `*` 表示 `0-N` ge; `?` 表示 `0/1` 个
     *
     * 2、 (d.getFullYear() + '').substr(4 - RegExp.$1.length))
     * - 判断正则匹配的字符串长度，截取年份字符串，正则匹配长度为 `1~3`、`5~7` 匹配结果为 `1~3` 位的年份字符串， `4,8,...` 为整个年份字符串
     *
     * 3、 _format = _format.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length));
     * - 替换所有 `y` 为上面匹配出的年份字符串的结果
     *
     */

  if (/(y+)/.test(_format)) {
    _format = _format.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length))
  }

  for (const k in o) {
    if (o.hasOwnProperty(k) && new RegExp('(' + k + ')').test(_format)) {
      _format = _format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
    }
  }

  return _format
}

/**
 * imgTrustUrl(url)
 * 在 `node` 服务上使用，判断 `开发环境/测试环境` 补全 `Url`，在前面加入服务器 `Url`
 *
 * 后续研究下如何扩展 `Java` 配置
 *
 */
export function imgTrustUrl(url) {
  if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
    return IMAGE_HOST_TEST + url
  } else if (process.env.NODE_ENV === 'production') {
    return IMAGE_HOST_PROD + url
  } else {
    return url
  }
}

export function isPromise(value) {
  if (value !== null && typeof value === 'object') {
    return value.promise && typeof value.promise.then === 'function'
  }
}

export function setCookie(cname, cvalue, exhours) {
  let date = new Date()
  date.setTime(date.getTime() + (exhours*60*60*1000))
  let expires = 'expires='+date.toUTCString()
  document.cookie = cname + '=' + escape(cvalue) + '; ' + expires
}
export function getCookie(name) {
  let value = '; ' + document.cookie
  let parts = value.split('; ' + name + '=')
  if (parts.length == 2) return unescape(parts.pop().split(';').shift()) 
}
export function delCookie($name){
  let myDate=new Date()
  myDate.setTime(-1000)//设置时间
  document.cookie=$name+'=\'\'; expires='+myDate.toGMTString()
}
export function delAllCookie(){
  let myDate=new Date()
  myDate.setTime(-1000)//设置时间
  let data=document.cookie
  let dataArray=data.split('; ')
  for(let i=0;i<dataArray.length;i++){
    let varName=dataArray[i].split('=')
    document.cookie=varName[0]+'=\'\'; expires='+myDate.toGMTString()
  }

}

export function addFieldsToObject(object, fields) {
  if (fields && typeof(fields) === 'object') {
    _.mapKeys(fields, function(value, key) {
      let componentValue = value.value
      object[key] = componentValue
    })
  }
  return object
}
export function objectTransformField(fields, object) {

  if (object && typeof(object) === 'object') {
    _.mapKeys(object, function(value, key) {
      fields[key] = {
        name: key,
        value: value
      }
    })
  }

  return fields
}

export function getNewTreeData(treeData, curKey, child, level) {

  const loop = (data) => {
    data.forEach((item) => {
      if (curKey.indexOf(item.key) === 0) {
        if (child.length == 0) {
          // message.info('提示：没有数据了！');
          item.isLeaf = true
        } else {
          item.children = child
        }
      } else {
        if (item.children) {
          loop(item.children)
        }
      }
    })
  }
  loop(Object.assign([], treeData))

  return treeData
}

export const setArraytoObj = (function f(params, str, num, callback) {

  if (num == 0) {
    return params
  }

  let temp = Object.assign({}, params)

  temp[str + num] = callback(temp, str, num)

  return f(temp, str, num - 1, callback)
})

export function getServerBase(){
  switch (process.env.NODE_ENV) {
    case 'dev': return 'http://10.79.21.29:8111'
    case 'test': return 'https://testcustomerservicebackend.crlandpm.com.cn'
    case 'staging': return 'https://precustomerservicebackend.crlandpm.com.cn'
    case 'prod': return 'https://customerservicebackend.crlandpm.com.cn'
    default: return 'http://localhost/api/'
  }
}

export function refreshCookie(){
  let user_token    = getCookie('token')
  let realName      = getCookie('realName')
  let orgUuid       = getCookie('orgUuid')
  let accountUuid   = getCookie('accountUuid')
  let communityUuid = getCookie('communityUuid')
  let communityName = getCookie('communityName')
  let account       = getCookie('account')
  delAllCookie()
  /**
     * 写cookies
     */
  setCookie('token', user_token, 10)
  setCookie('realName', realName, 10)
  setCookie('orgUuid', orgUuid, 10)
  setCookie('accountUuid', accountUuid, 10)
  setCookie('account', account, 10)
  setCookie('communityUuid', communityUuid, 10)
  setCookie('communityName', communityName, 10)
}


/**
 * 根据当前页面地址，获取
 * @param {*} key 
 */
export function getKey(key){
    switch(key){
        case "building":
        case "houseDetail":
        case "house":
            return "house";
            break;
        case "index":
        case "sltp":
        case "slt":
            return "index";
            break;
        case "repair":
        case "addRepair":
        case "orderdetail":
            return "repair";
            break;
        default : return "taskCreate";
    }
}

/*2017.4.27 鼠标经过canvas特效*/
//定义画布宽高和生成点的个数
export function  canvas(){
   var WIDTH = window.innerWidth, HEIGHT = window.innerHeight, POINT = 35;

  var circleArr = [];
  //线条：开始xy坐标，结束xy坐标，线条透明度
  function Line (x, y, _x, _y, o) {
    this.beginX = x,
    this.beginY = y,
    this.closeX = _x,
    this.closeY = _y,
    this.o = o;
  }
  //点：圆心xy坐标，半径，每帧移动xy的距离
  function Circle (x, y, r, moveX, moveY) {
    this.x = x,
    this.y = y,
    this.r = r,
    this.moveX = moveX,
    this.moveY = moveY;
  }
  //生成max和min之间的随机数
  function num (max, _min) {
    var min = arguments[1] || 0;
    return Math.floor(Math.random()*(max-min+1)+min);
  }
  // 绘制原点
  function drawCricle (cxt, x, y, r, moveX, moveY) {
    var circle = new Circle(x, y, r, moveX, moveY)
    cxt.beginPath()
    cxt.arc(circle.x, circle.y, circle.r, 0, 2*Math.PI)
    cxt.closePath()
    cxt.fill();
    return circle;
  }
  //绘制线条
  function drawLine (cxt, x, y, _x, _y, o) {
    var line = new Line(x, y, _x, _y, o)
    cxt.beginPath()
    cxt.strokeStyle = 'rgba(0,0,0,'+ o +')'
    cxt.moveTo(line.beginX, line.beginY)
    cxt.lineTo(line.closeX, line.closeY)
    cxt.closePath()
    cxt.stroke();

  }
  //初始化生成原点
  function init () {
    var canvas = document.getElementById('canvas');
    canvas.width = WIDTH,
    canvas.height = HEIGHT;
    var context = canvas.getContext('2d');
    context.strokeStyle = 'rgba(0,0,0,0.02)',
    context.strokeWidth = 1,
    context.fillStyle = 'rgba(0,0,0,0.05)';
    circleArr = [];
    for (var i = 0; i < POINT; i++) {
      circleArr.push(drawCricle(context, num(WIDTH), num(HEIGHT), num(15, 2), num(10, -10)/40, num(10, -10)/40));
    }
    draw(canvas,context);
    return {
      canvas: canvas,
      context: context
    }
  }

  //每帧绘制
  function draw (canvas,context) {
    context.clearRect(0,0,canvas.width, canvas.height);
    for (var i = 0; i < POINT; i++) {
      drawCricle(context, circleArr[i].x, circleArr[i].y, circleArr[i].r);
    }
    for (var i = 0; i < POINT; i++) {
      for (var j = 0; j < POINT; j++) {
        if (i + j < POINT) {
          var A = Math.abs(circleArr[i+j].x - circleArr[i].x),
            B = Math.abs(circleArr[i+j].y - circleArr[i].y);
          var lineLength = Math.sqrt(A*A + B*B);
          var C = 1/lineLength*7-0.009;
          var lineOpacity = C > 0.03 ? 0.03 : C;
          if (lineOpacity > 0) {
            drawLine(context, circleArr[i].x, circleArr[i].y, circleArr[i+j].x, circleArr[i+j].y, lineOpacity);
          }
        }
      }
    }
  }

  //调用执行
  window.onload = function () {
    var obj = init();
    setInterval(function () {
      for (var i = 0; i < POINT; i++) {
        var cir = circleArr[i];
        cir.x += cir.moveX;
        cir.y += cir.moveY;
        if (cir.x > WIDTH) cir.x = 0;
        else if (cir.x < 0) cir.x = WIDTH;
        if (cir.y > HEIGHT) cir.y = 0;
        else if (cir.y < 0) cir.y = HEIGHT;
        
      }
      draw(obj.canvas,obj.context);
    }, 10);
  }
}